package com.zhugang.week13.queue;

import com.zhugang.week13.stack.Stack;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @program algorithms
 * @description: QueueByStack
 * @author: chanzhugang
 * @create: 2022/10/08 18:38
 */
public class QueueByStack<T> {
    /**
     * 两个栈实现队列
     */
    Stack<T> stack1 = new Stack<>();
    Stack<T> stack2 = new Stack<>();


    public void enqueue(T e) {
        stack1.push(e);
    }

    public T dequeue() {
        if (stack2.size() > 0) {
            return stack2.pop();
        }
        // 如果栈2为null， 把栈1的数据弹出放入栈2
        while (stack1.size() > 0) {
            stack2.push(stack1.pop());
        }
        return stack2.pop();
    }

    @Test
    public void test() {
        var queue = new QueueByStack<>();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        queue.enqueue(4);

        assertEquals(1, queue.dequeue());
        assertEquals(2, queue.dequeue());
        assertEquals(3, queue.dequeue());
        assertEquals(4, queue.dequeue());

    }
}